﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;

namespace DataAccess
{
    public class UserRepository : ConnectionClass
    {
        public UserRepository() : base() { }

        //-----------------------------REGISTRATION METHODS----------------------
        public void Register(User u)
        {
            entity.AddToUsers(u);
            entity.SaveChanges();
        }

        public void AllocateRole(User user, Common.Type type)
        {   
            user.Types.Add(type);
            entity.SaveChanges();
        }

        public Common.Type GetRole(int typeID)
        {
            //get the role by searching by ID
            return entity.Types.SingleOrDefault(x => x.ID == typeID);
        }

        public IEnumerable<Country> GetCountries()
        {
            return entity.Countries;
        }

        public bool DoesEmailExist(string email)
        {
            bool result = false;

            if (entity.Users.Count(u => u.Email == email) == 0)
            {
                result = true;
            }

            return result;
          
        }

        public bool DoesUsernameExist(string username)
        {
            bool result = false;

            if (entity.Users.Count(u => u.Username == username) == 0)
            {
                result = true;
            }

            return result;
        }

        public Common.Type getUserType(int id)
        {
            return entity.Types.SingleOrDefault(x => x.ID == id);
        }

        //-------------------------LOGIN METHODS-------------------------

        public bool UserAuthentication(string username, string password)
        {
            try
            {
                if (entity.Users.SingleOrDefault(u=> u.Username == username && u.Password == password) == null)
                {
                    return false;
                }
                else return true;

            }
            catch (Exception ex)
            {
                throw ex.InnerException;
            }
        }

        public User GetUserByUsername(string username)
        {
            return entity.Users.SingleOrDefault(u => u.Username == username);
        }
    }
}
